package com.jwthhealth_pub.home.view;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.jwthhealth_pub.R;
import com.jwthhealth_pub.app.App;
import com.jwthhealth_pub.app.module.ThraPreviewModule;
import com.jwthhealth_pub.app.view.MainActivity;
import com.jwthhealth_pub.common.JwthImgLoader;
import com.jwthhealth_pub.common.LogUtil;
import com.jwthhealth_pub.common.base.BasetFragment;
import com.jwthhealth_pub.common.preference.PreferenceKey;
import com.jwthhealth_pub.common.view.JwthBannerBottom;
import com.jwthhealth_pub.common.view.JwthMarqueeView;
import com.jwthhealth_pub.common.view.TitleLayout;
import com.jwthhealth_pub.community.view.CommunityActivity;
import com.jwthhealth_pub.guardian.view.DetailsGuardianActivity;
import com.jwthhealth_pub.home.model.TopCase;
import com.jwthhealth_pub.home.presenter.HomePresenter;
import com.jwthhealth_pub.home.presenter.HomePresenterCompl;
import com.jwthhealth_pub.home.view.adapter.HomeMsgAdapter;
import com.jwthhealth_pub.old.api.ApiHelper;
import com.jwthhealth_pub.old.common.Constant;
import com.jwthhealth_pub.old.constitution.view.ConstitutionActivity;
import com.jwthhealth_pub.old.healthyscreening.view.HealthyScreeningActivity;
import com.jwthhealth_pub.old.heartscreen.view.HeartScreenActivity;
import com.jwthhealth_pub.old.physicalfitness.view.PhysicalFitnessActivity;
import com.jwthhealth_pub.old.report.model.resbody.HraDateRes;
import com.jwthhealth_pub.old.report.view.FoodSuggestActivity;
import com.jwthhealth_pub.old.report.view.NewReportInfoActivity;
import com.jwthhealth_pub.old.report.view.SportSuggestActivity;
import com.jwthhealth_pub.old.sign.model.LoginModel;
import com.jwthhealth_pub.old.sign.view.SignInActivity;
import com.jwthhealth_pub.old.signutil.model.db.UserInfoDao;
import com.jwthhealth_pub.old.subscribe.SubscribeActivity;
import com.jwthhealth_pub.utils.Contas;
import com.jwthhealth_pub.wristband.main.view.WristbandMainActivity;
import com.jwthhealth_pub.wristband.setting.view.WristBandConnManaActivity;
import com.jwthhealth_pub.wristband.view.WristBandSettingUserInfoActivity;
import com.youth.banner.Banner;
import com.youth.banner.listener.OnBannerClickListener;
import com.youth.banner.loader.ImageLoader;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindArray;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import static com.jwthhealth_pub.common.LogUtil.makeLogTag;


/**
 * 首页
 * Created by liuzhen on 2017/12/4.
 */

public class HomeFrgment extends BasetFragment implements HomePresenter.View {

    public static final int WRISTBAND_CONN_USERINFO = 0;
    public static final int WRISTBAND_CONN_DEV = 1;

    private static final String banner_img_one = "http://192.168.1.108//uploads/20171012/dXNlclVwbG9hZDE1MDc3OTE2NDE4ODcyMzMxNTE0.jpg";
    private static final String banner_img_two = "http://192.168.1.108//uploads/20170829/dXNlclVwbG9hZDE1MDM5OTY4Njk5MDgwNDg1ODM4.jpg";
    private static final String banner_img_thi = "http://192.168.1.108//uploads/20171013/dXNlclVwbG9hZDE1MDc4NzUxNDUzNDA4NzE5NjE5.jpg";
    private static final String banner_img_for = "http://192.168.1.108//uploads/20171013/dXNlclVwbG9hZDE1MDc4NzUzOTI2NjE0NjM1MjE=.jpg";
    private static final String banner_img_fiv = "http://192.168.1.108//uploads/20171013/dXNlclVwbG9hZDE1MDc4NzQwOTA4NTUxODM0OTc5.jpg";

    private static final String TAG = makeLogTag(HomeFrgment.class);

    @BindView(R.id.banner_home)
    Banner bannerHome;
    @BindView(R.id.banner_bottom_home)
    JwthBannerBottom bannerBottom;
    @BindView(R.id.marqueeview_home)
    JwthMarqueeView marqueeView;
    @BindView(R.id.layout_checkonline_btns_homes)
    LinearLayout layoutCheckonlineBtns;
    @BindView(R.id.layout_hot_btns_homes)
    LinearLayout layoutHotBtns;
    @BindView(R.id.rv_home_msg)
    RecyclerView rvMsg;
    @BindView(R.id.title_layout)
    TitleLayout titleLayout;

    @BindArray(R.array.home_check_online)
    String[] checkOnlineBtnNames;

    Unbinder unbinder;
    @BindView(R.id.iv_check_online)
    ImageView ivCheckOnline;
    @BindView(R.id.tv_title_check_online)
    TextView tvTitleCheckOnline;
    @BindView(R.id.iv_hot)
    ImageView ivHot;
    @BindView(R.id.tv_title_hot)
    TextView tvTitleHot;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_home, container, false);
        unbinder = ButterKnife.bind(this, view);

        HomePresenter.Presenter mHomePresenter = new HomePresenterCompl(this);
        mHomePresenter.getBanner();
        mHomePresenter.getHeadLine();
        mHomePresenter.getMsg();
        showCheckOnlineBtns();
        showHotBtns();

        return view;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @Override
    public void showBanner() {
        // TODO: 2017/12/5 根据屏幕的大小调整banner的尺寸

        List<Object> images = new ArrayList<>();
        images.add(banner_img_one);
        images.add(banner_img_two);
        images.add(banner_img_thi);
        images.add(banner_img_for);
        images.add(banner_img_fiv);

        bannerBottom.setmPointSize(images.size());
        bannerHome.setDelayTime(3000);
        bannerHome.setIndicatorGravity(Gravity.BOTTOM);

        bannerHome.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
//                Log.d(TAG, "onPageScrolled position:" + position);
            }

            @Override
            public void onPageSelected(int position) {
                if (bannerBottom == null) return;
                bannerBottom.setmSelectPos(position);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

        OnBannerClickListener listener = new OnBannerClickListener() {
            @Override
            public void OnBannerClick(int position) {
                Toast.makeText(getActivity(), "click", Toast.LENGTH_SHORT).show();
            }
        };

        bannerHome.setImages(images)
                .setImageLoader(new BannderImgLoader())
                .setOnBannerClickListener(listener)
                .start();
    }

    @Override
    public void showHeadLine() {
        final List<String> headLineData = new ArrayList<>();
        final  List<View> views = new ArrayList<>();
        Call<TopCase> topCase = ApiHelper.getTopCase();
        topCase.enqueue(new Callback<TopCase>() {
            @Override
            public void onResponse(Call<TopCase> call, Response<TopCase> response) {
                TopCase body = response.body();
                if (body == null) return;
                if (body.getCode().equals("0")){
                    final List<TopCase.Case> list =  body.getData().getTop_case();
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            for (int i = 0; i < list.size(); i++) {
                                headLineData.add(list.get(i).getTitle());
                            }
                            for (int i = 0; i < headLineData.size(); i = i + 2) {
                                final int position = i;
                                //设置滚动的单个布局
                                LinearLayout moreView = (LinearLayout) LayoutInflater.from(getActivity()).inflate(R.layout.item_home_headline_view, null);
                                //初始化布局的控件
                                TextView tv1 = moreView.findViewById(R.id.tv1);
                                TextView tv2 = moreView.findViewById(R.id.tv2);

                                moreView.findViewById(R.id.rl).setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View view) {
                                        Toast.makeText(getActivity(), headLineData.get(position), Toast.LENGTH_SHORT).show();
                                    }
                                });

                                moreView.findViewById(R.id.rl2).setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View view) {
                                        Toast.makeText(getActivity(), headLineData.get(position + 1), Toast.LENGTH_SHORT).show();
                                    }
                                });
                                //进行对控件赋值
                                tv1.setText(headLineData.get(i));
                                if (headLineData.size() > i + 1) {
                                    //因为淘宝那儿是两条数据，但是当数据是奇数时就不需要赋值第二个，所以加了一个判断，还应该把第二个布局给隐藏掉
                                    tv2.setText(headLineData.get(i + 1));
                                } else {
                                    moreView.findViewById(R.id.rl2).setVisibility(View.GONE);
                                }

                                //添加到循环滚动数组里面去
                                views.add(moreView);

                                marqueeView.setViews(views);
                                marqueeView.setOnItemClickListener(new JwthMarqueeView.OnItemClickListener() {
                                    @Override
                                    public void onItemClick(int position, View view) {
                                        Toast.makeText(getActivity(), "你点击了第几个items" + position, Toast.LENGTH_SHORT).show();
                                    }
                                });
                            }

                        }
                    });
                }
            }

            @Override
            public void onFailure(Call<TopCase> call, Throwable t) {
                Log.i("tag",t.getMessage());
            }
        });
    }

    @Override
    public void showCheckOnlineBtns() {
        layoutCheckonlineBtns.removeAllViews();
        for (int i = 0; i < checkOnlineBtnNames.length; i++) {
            layoutCheckonlineBtns.addView(getCheckOnlineBtns(i));
        }
    }

    @Override
    public void showHotBtns() {
        layoutHotBtns.removeAllViews();
        // TODO: 2017/12/6 2
        for (int i = 0; i < 2; i++) {
            layoutHotBtns.addView(getHotBtn(i));
        }
    }

    @Override
    public void showMsgs() {
        rvMsg.setLayoutManager(new LinearLayoutManager(getActivity()));
        rvMsg.setAdapter(new HomeMsgAdapter((MainActivity) getActivity()));
    }

    private Button getCheckOnlineBtns(final int i) {
        Button btn = new Button(getActivity());

        int screenWid = App.preferenceUtil.getInt(PreferenceKey.SCREEN_WIDTH, 0);

        if (screenWid == 0) return btn;

        double unitWid = screenWid / 2.2;

        int btnWid = (int) (unitWid * .95);
        int btnHei = (int) (btnWid / 1.6);
        int btnSpace = (int) (unitWid * .05);


        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(btnWid, btnHei);
        layoutParams.setMargins(btnSpace, 0, 0, 0);
        btn.setLayoutParams(layoutParams);

        switch (i) {
            case 0:
                btn.setBackgroundResource(R.mipmap.btn_home_check_healthscreening);
//                btn.setText(R.string.btn_home_check_online_health);
                break;
            case 1:
                btn.setBackgroundResource(R.mipmap.btn_home_check_heart);
//                btn.setText(R.string.btn_home_check_online_heart);
                break;
            case 2:
                btn.setBackgroundResource(R.mipmap.btn_home_check_chinesephysical);
//                btn.setText(R.string.btn_home_check_online_chinese_physical);
                break;
            case 3:
                btn.setBackgroundResource(R.mipmap.btn_home_check_physique);
//                btn.setText(R.string.btn_home_check_online_physical);

                LinearLayout.LayoutParams layoutParams1 = (LinearLayout.LayoutParams) btn.getLayoutParams();
                layoutParams1.setMargins(btnSpace, 0, btnSpace, 0);
                btn.setLayoutParams(layoutParams);

                break;
            default:
                break;
        }

        btn.setText(checkOnlineBtnNames[i]);
        btn.setTextAppearance(getActivity(), R.style.home_check_online_btn);

        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                switch (i) {
                    case 0:
                        //健康筛查入口
                        startActivity(new Intent(getActivity(), HealthyScreeningActivity.class));
                        break;
                    case 1:
                        //心肺耐力
                        startActivity(new Intent(getActivity(), HeartScreenActivity.class));
                        break;
                    case 2:
                        //中医体质
                        startActivity(new Intent(getActivity(), ConstitutionActivity.class));
                        break;
                    case 3:
                        //体适能问卷
                        startActivity(new Intent(getActivity(), PhysicalFitnessActivity.class));
                        break;
                    default:
                        break;
                }
            }
        });

        return btn;
    }

    private View getHotBtn(final int count) {
        View hotBtn = new View(getActivity());

        int screenWid = App.preferenceUtil.getInt(PreferenceKey.SCREEN_WIDTH, 0);

        if (screenWid == 0) return hotBtn;

        double unitWid = screenWid / 2.1;

        int btnWid = (int) (unitWid * .95);
        int btnHei = (int) (btnWid / 2.36);
        int btnSpace = (int) (unitWid * .05);

        hotBtn = View.inflate(getActivity(), R.layout.item_hot_view, null);
        TextView tvHotTitle = hotBtn.findViewById(R.id.tv_item_hot_title);
        TextView tvHotDescribe = hotBtn.findViewById(R.id.tv_item_hot_describe);
        RelativeLayout layoutHot = hotBtn.findViewById(R.id.layout_hot);

        // TODO: 2017/12/17
        if (count == 0) {
            tvHotTitle.setText("膳食建议");
            tvHotDescribe.setText("食疗是根本");
        } else {
            tvHotTitle.setText("运动建议");
            tvHotDescribe.setText("运动也是根本");
        }
//        tvHotTitle.setTextColor(Color.WHITE);

        layoutHot.setBackgroundResource(R.mipmap.temp_hot_bg);

        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(btnWid, btnHei);
        layoutParams.setMargins(btnSpace, 0, 0, 0);
        hotBtn.setLayoutParams(layoutParams);

        // TODO: 2017/12/6  1
        if (count == 1) {
            LinearLayout.LayoutParams layoutParams1 = (LinearLayout.LayoutParams) hotBtn.getLayoutParams();
            layoutParams1.setMargins(btnSpace, 0, btnSpace, 0);
            hotBtn.setLayoutParams(layoutParams);
        }

        hotBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ThraPreviewModule.DataBean dataBean = Contas.getObject(getActivity(), ThraPreviewModule.DataBean.class);
                if (dataBean == null)
                    return;

                String nid = dataBean.getResult().getNid();
                if (nid == null) return;

                Intent intent = null;
                if (count == 0) {
                    intent = new Intent(getActivity(), FoodSuggestActivity.class);
                } else if (count == 1) {
                    intent = new Intent(getActivity(), SportSuggestActivity.class);
                }

                if (intent != null) {
                    intent.putExtra("id", nid);
                    startActivity(intent);
                }
            }
        });

        return hotBtn;
    }

    @OnClick({R.id.btn_home_thra, R.id.btn_home_wristband, R.id.btn_home_subscribe,
            R.id.btn_home_personalhealth, R.id.btn_home_watchrelation})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_home_thra:
                LoginModel.DataBean dataBean5 = UserInfoDao.getInstance().queryUserinfoModel();
                if (dataBean5 == null) {
                    Toast.makeText(getActivity(), "请先登陆", Toast.LENGTH_SHORT).show();

                    Intent intent = new Intent(getActivity(), SignInActivity.class);
                    intent.putExtra(Constant.SIGN_JUMP_TOKEN, "0");
                    startActivity(intent);
                    return;
                }


//                HashMap<String, String> params = new LinkedHashMap<>();
                LoginModel.DataBean userinfoModel = UserInfoDao.getInstance().queryUserinfoModel();
//                params.put("dev", ApiHelper.deviceId);
//                params.put("mac", ApiHelper.macAddress);
//                params.put("uid", userinfoModel.getId());
//                String sign = ReqUtil.getSign(params, userinfoModel.getAndroidtoken());
//                RequestService requestService = RequestHelper.getmRequestHelper();
                Call<HraDateRes> call = ApiHelper.getNewHraDate(userinfoModel.getId(), userinfoModel.getAndroidtoken());
//                Call<HraDate> call = ApiHelper.getHraDate(userinfoModel.getId(), userinfoModel.getAndroidtoken());
                call.enqueue(new Callback<HraDateRes>() {
                    @Override
                    public void onResponse(@NonNull Call<HraDateRes> call, @NonNull Response<HraDateRes> response) {
                        Intent intent3 = new Intent(getActivity(), NewReportInfoActivity.class);
//                        Intent intent3 = new Intent(mActivity, IndividualHealthReportActivity.class);
                        HraDateRes body = response.body();
                        if (body == null) return;
                        if (body.getCode() == null || body.getData() == null) return;
                        if (body.getCode().equals("0")) {
                            intent3.putParcelableArrayListExtra("datalist", (ArrayList<? extends Parcelable>) body.getData());
                            intent3.putExtra(Constant.ISRETEXT, true);
                            startActivity(intent3);
//                            progressBar.setVisibility(View.GONE);
                        } else {
                            Log.e(TAG, body.getMsg());
                            LogUtil.toast(body.getMsg());
//                            progressBar.setVisibility(View.GONE);
                        }
                    }

                    @Override
                    public void onFailure(@NonNull Call<HraDateRes> call, @NonNull Throwable t) {
                        Log.e(TAG, t.toString());
//                        progressBar.setVisibility(View.GONE);
                    }
                });

                break;
            case R.id.btn_home_wristband:
                startActivity(new Intent(getActivity(), WristbandMainActivity.class));

//                UserInfoModel userInfo = Contas.getObject(getActivity(), UserInfoModel.class);

//                if (userInfo != null && userInfo.isNecessityInfoComplete()) {
//                    if (WristBandService.isConn) {
//                        // 手环连接
//                        startActivity(new Intent(getActivity(), WristbandMainActivity.class));
//                    } else {
//                        // 手环未连接
//                        startActivityForResult(new Intent(getActivity(), WristBandConnManaActivity.class), WRISTBAND_CONN_DEV);
//                    }
//                } else {
//                    startActivityForResult(new Intent(getActivity(), WristBandSettingUserInfoActivity.class), WRISTBAND_CONN_USERINFO);
//                }
                break;
            case R.id.btn_home_subscribe:
                if (App.preferenceUtil.getBoolean(PreferenceKey.CACHE_TOKEN, false)) {
                    Intent intent = new Intent(getActivity(), SubscribeActivity.class);
                    startActivity(intent);
                } else {
                    Toast.makeText(getActivity(), getResources().getString(R.string.diet_sign), Toast.LENGTH_SHORT).show();
                    Intent intent = new Intent(getActivity(), SignInActivity.class);
                    intent.putExtra(Constant.SIGN_JUMP_TOKEN, SignInActivity.FROM_HOME);
                    startActivity(intent);
                }
                break;
            case R.id.btn_home_personalhealth:
                startActivity(new Intent(getActivity(), CommunityActivity.class));
                break;
            case R.id.btn_home_watchrelation:
                startActivity(new Intent(getActivity(), DetailsGuardianActivity.class));
                break;
        }
    }
    @Override
    protected void title() {
        titleLayout.setOnTitleLayoutListener(new TitleLayout.TitleLayoutListener() {
            @Override
            public void leftclick() {
            }

            @Override
            public void leftTextClick() {

            }

            @Override
            public void rightclick() {
//                // TODO: 2017/12/19 右击有bug
//                startActivity(new Intent(getActivity(), CommunityActivity.class));
            }

            @Override
            public void rightTextClick() {
//                startActivity(new Intent(getActivity(), CommunityActivity.class));
            }
        });
    }

    private class BannderImgLoader extends ImageLoader {

        @Override
        public void displayImage(Context context, Object path, ImageView imageView) {
            String imgPath = String.valueOf(path);
//            Picasso.with(context).load(imgPath).into(imageView);
            Log.d("MyImageLoader", imgPath);
            JwthImgLoader.picasso(imgPath, imageView);
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case WRISTBAND_CONN_USERINFO:
                if (resultCode == WristBandSettingUserInfoActivity.RESULT_OK) {
                    Intent intent = new Intent(getActivity(), WristBandConnManaActivity.class);
                    startActivityForResult(intent, WRISTBAND_CONN_DEV);
                }
                break;
            case WRISTBAND_CONN_DEV:
                if (requestCode == WristBandConnManaActivity.RESULT_OK) {
                    Toast.makeText(getActivity(), "手环已经连接", Toast.LENGTH_SHORT).show();
                    Intent intent = new Intent(getActivity(), WristBandConnManaActivity.class);
                    startActivity(intent);
                }
                break;
            default:break;
        }
    }
}